import random
import time

from selenium.common import NoSuchElementException, ElementClickInterceptedException

from h5_order.client.web_client import WebClient
from h5_order.constants.common_constants import SWITCH_URL
from selenium.webdriver.common.by import By
from multiprocessing import Process


def retry_until_success(brower, by, locator, max_retries=None, retry_interval=2):
    """
    不断重试找到并点击元素，直到成功或达到最大重试次数。
    Params:
    -brower：浏览器
    -by: 选取元素的方式
    -locator:定位元素
    -max_retries:重试次数
    """
    retries = 0
    while True:
        try:
            element = brower.find_element(by, locator)
            element.click()
            print(f"Element {locator} clicked successfully.")
            break  # 成功后退出循环
        except (NoSuchElementException, ElementClickInterceptedException) as e:
            retries += 1
            print(f"Attempt {retries}: {e}. Retrying...")
            if max_retries and retries >= max_retries:
                print("Reached maximum retry limit. Exiting.")
                raise
            time.sleep(retry_interval)
        except Exception as e:
            print(f"Unexpected error: {e}")
            raise


def take_order_amount():
    """
    下单数量
    """
    brower = WebClient().brower
    brower.get(SWITCH_URL)
    random_integer = random.randint(1, 2)
    # 进入下单
    retry_until_success(brower, By.CLASS_NAME, locator='contentindex-bottom', retry_interval=2)
    my_list = [('/html/body/uni-app/uni-page/uni-page-wrapper/uni-page-body/uni-view/uni-view[4]/uni-scroll-view[1]/div/div/div/uni-view[2]', 'item1'),
               ('/html/body/uni-app/uni-page/uni-page-wrapper/uni-page-body/uni-view/uni-view[4]/uni-scroll-view[1]/div/div/div/uni-view[1]', 'item0'),
               ('/html/body/uni-app/uni-page/uni-page-wrapper/uni-page-body/uni-view/uni-view[4]/uni-scroll-view[1]/div/div/div/uni-view[3]', 'item2'),
               ('/html/body/uni-app/uni-page/uni-page-wrapper/uni-page-body/uni-view/uni-view[4]/uni-scroll-view[1]/div/div/div/uni-view[4]', 'item3')]

    # 选前两个即可
    for item in range(random_integer):
        random_choice = random.choice(my_list)
        retry_until_success(brower, By.XPATH,
                            locator=random_choice[0],
                            retry_interval=2)
        if item == 0:
            random_integer = random.randint(2, 3)
            retry_until_success(brower, By.CSS_SELECTOR,
                                f'#{random_choice[1]} > uni-view:nth-child({random_integer}) > uni-view > uni-view.item-goods-img-list > uni-view.cart-but.newbut > uni-view > uni-view')
            retry_until_success(brower, By.CLASS_NAME,
                                locator='goods_info_button',
                                retry_interval=2)
        else:
            random_integer = random.randint(2, 3)
            retry_until_success(brower, By.CSS_SELECTOR,
                                locator=f'{random_choice[1]} > uni-view:nth-child({random_integer}) > uni-view > uni-view.item-goods-img-list > uni-view.cart-but.newbut > uni-view.but.add',
                                retry_interval=2)
        retry_until_success(brower, By.CLASS_NAME,
                            locator='goods_info_button',
                            retry_interval=2)
    # for item1 in range(random_integer1):
    #     if item1 == 0:
    #         retry_until_success(brower, By.XPATH,
    #                             locator='//*[@id="item0"]/uni-view[3]/uni-view/uni-view[2]/uni-view[3]/uni-view/uni-view',
    #                             retry_interval=2)
    #     else:
    #         retry_until_success(brower, By.XPATH,
    #                             locator='//*[@id="item0"]/uni-view[3]/uni-view/uni-view[2]/uni-view[3]/uni-view[3]',
    #                             retry_interval=2)
    #     retry_until_success(brower, By.CLASS_NAME,
    #                         locator='goods_info_button',
    #                         retry_interval=2)
    # retry_until_success(brower, By.CLASS_NAME,
    #                     locator='cart-listicon',
    #                     retry_interval=2)
    # retry_until_success(brower, By.XPATH,
    #                     locator='/html/body/uni-app/uni-page/uni-page-wrapper/uni-page-body/uni-view/uni-view[4]/uni-view[1]/uni-view[1]/uni-view/uni-view',
    #                     retry_interval=2)
    # retry_until_success(brower, By.XPATH,
    #                     locator='/html/body/uni-app/uni-page/uni-page-wrapper/uni-page-body/uni-view/uni-view[4]/uni-view[2]/div/uni-button',
    #                     retry_interval=2)


if __name__ == '__main__':
    for item in range(1):
        for record in range(1):
            Process(target=take_order_amount).start()
        time.sleep(20)
